<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :title="formData.id ? '编辑菜单' : '添加菜单'"
    size="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="菜品名称：" prop="name">
        <el-input v-model="formData.name" placeholder="请输入菜品名称" />
      </el-form-item>
      <el-form-item label="菜品分类：" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择菜品分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜品价格：" prop="price">
        <el-input v-model="formData.price" placeholder="请输入菜品价格" />
      </el-form-item>
      <el-form-item label="口味选择：" prop="flavors">
        <div
          v-if="formData.flavors && formData.flavors.length > 0"
          class="flavors-container"
        >
          <div
            v-for="(flavor, index) in formData.flavors"
            :key="index"
            class="flavor-item"
          >
            <el-autocomplete
              v-model="formData.flavors[index].name"
              :fetch-suggestions="flavorSuggestions"
              placeholder="请输入口味"
              clearable
              trigger-on-focus
              value-key="name"
              :debounce="0"
              highlight-first-item
              popper-class="flavor-autocomplete-popper"
              style="width: 150px"
              @select="handleSelectFlavor"
            />
            <el-select
              v-model="formData.flavors[index].value"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入口味描述"
            >
              <el-option
                v-for="item in flavorValue"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              circle
              @click="removeFlavor(index)"
            />
          </div>
        </div>
        <el-button type="primary" size="small" @click="addFlavor">
          <span>添加口味</span>
        </el-button>
      </el-form-item>
      <el-form-item label="图片:" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          accept="image/jpeg,image/png"
        >
          <img
            v-if="formData.image"
            :src="`${env}/common/download?name=${formData.image}`"
            class="avatar"
          />
          <div v-else class="avatar-uploader-icon">
            <i class="el-icon-plus" />
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜品描述：" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入菜品描述"
        />
      </el-form-item>
    </el-form>
    <div
      style="
        display: flex;
        justify-content: flex-end;
        gap: 16px;
        margin: 40px 0 0 0;
      "
    >
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :loading="submitLoading"
        style="width: 88px"
        @click="handleSubmit"
      >
        {{ formData.id ? "更新" : "添加" }}
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
import {
  addMenu,
  updateMenu,
  getCategoryList,
  getMenuDetail,
} from "@/api/menu";
import { Message } from "element-ui";

export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      env: process.env.VUE_APP_BASE_API,
      formRef: null,
      submitLoading: false,
      drawerVisible: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      imageUrl: "",
      formData: {
        id: null,
        name: "", // 菜品名称
        categoryId: null, // 菜品分类ID
        code: "",
        price: "", // 菜品价格
        status: 1, // 售卖状态
        description: "", // 菜品描述
        flavors: [], // 口味数组
        image: "", // 图片
      },
      formRules: {
        name: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择菜品分类", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入菜品价格", trigger: "blur" },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "请输入正确的价格格式",
            trigger: "blur",
          },
        ],
        // flavors: [{ required: true, message: '请输入口味', trigger: 'blur' }],
        description: [
          { required: true, message: "请输入菜品描述", trigger: "blur" },
        ],
        image: [{ required: false, message: "请上传图片", trigger: "blur" }],
      },
      categoryList: [],
      defaultFlavorOptions: [
        { name: "辣度", value: ["不辣", "微辣", "中辣", "重辣", "特辣"] },
        { name: "甜度", value: ["不甜", "微甜", "中甜", "重甜", "特甜"] },
        { name: "酸度", value: ["不酸", "微酸", "中酸", "重酸", "特酸"] },
        { name: "咸度", value: ["不咸", "微咸", "中咸", "重咸", "特咸"] },
        { name: "苦度", value: ["不苦", "微苦", "中苦", "重苦", "特苦"] },
        { name: "麻度", value: ["不麻", "微麻", "中麻", "重麻", "特麻"] },
      ],
      flavorValue: [],
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.drawerVisible = newVal;
      },
    },
    row: {
      immediate: true,
      handler(newVal) {
        // 判断是否为更新
        if (newVal && Object.keys(newVal).length) {
          const { id } = newVal;
          getMenuDetail(id).then((res) => {
            this.formData = res.data;
            this.formData.flavors = this.formData.flavors.map((flavor) => ({
              ...flavor,
              value: JSON.parse(flavor.value),
            }));
          });
        } else {
          // 新增，重置表单
          this.$nextTick(() => this.resetForm());
        }
      },
    },
  },
  mounted() {
    getCategoryList().then((res) => {
      this.categoryList = res.data;
    });
  },
  methods: {
    handleSelectFlavor(item) {
      this.flavorValue = this.defaultFlavorOptions.find(
        (flavor) => flavor.name === item.name
      ).value;
    },
    flavorSuggestions(queryString, cb) {
      let results = [];
      if (queryString) {
        // 如果有搜索内容，使用模糊匹配
        results = this.defaultFlavorOptions
          .filter((item) => item.name.includes(queryString))
          .map((item) => ({ name: item.name }));
      } else {
        // 如果没有搜索内容，返回所有选项
        results = this.defaultFlavorOptions.map((item) => ({
          name: item.name,
        }));
      }
      console.log(results, "results");
      cb(results);
    },
    updateMenu,
    addMenu,
    resetForm() {
      this.formData = {
        id: null,
        name: "", // 菜品名称
        categoryId: null, // 菜品分类ID
        code: "",
        price: "", // 菜品价格
        status: 1, // 售卖状态
        description: "", // 菜品描述
        flavors: [], // 口味数组
        image: "", // 图片
      };
    },
    handleClose() {
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.resetForm();
      this.drawerVisible = false;
      this.$emit("closed");
    },
    // 添加口味
    addFlavor() {
      if (!this.formData.flavors) {
        this.$set(this.formData, "flavors", []);
      }
      this.formData.flavors.push({ name: "", value: "" });
    },
    // 删除口味
    removeFlavor(index) {
      this.formData.flavors.splice(index, 1);
    },
    // 图片上传成功回调
    handleAvatarSuccess(res, file) {
      this.formData.image = res.data;
      Message.success("图片上传成功!");
    },
    // 图片上传失败回调
    handleAvatarError(error, file) {
      console.error("图片上传失败:", error);
      Message.error("图片上传失败!");
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate();
        this.submitLoading = true;
        // 处理口味数据，将口味值转换为JSON数组
        const processedFlavors = (this.formData.flavors || [])
          .filter(
            (flavor) => flavor && flavor.name && flavor.name.trim() !== ""
          )
          .map((flavor) => {
            let valueArray = [];
            if (flavor.value) {
              if (Array.isArray(flavor.value)) {
                // 如果已经是数组，直接使用
                valueArray = flavor.value.filter(
                  (item) => item && item.trim() !== ""
                );
              } else if (typeof flavor.value === "string") {
                // 如果是字符串，按逗号分割
                valueArray = flavor.value
                  .split(",")
                  .map((item) => item.trim())
                  .filter((item) => item);
              }
            }
            return {
              name: flavor.name,
              value: JSON.stringify(valueArray),
              showOption: false,
            };
          });

        const submitData = {
          ...this.formData,
          flavors: processedFlavors,
        };
        const api = this.formData.id ? updateMenu : addMenu;
        await api(submitData);
        Message.success(this.formData.id ? "更新成功" : "添加成功");
        this.$emit("success");
        this.handleClose();
      } catch (error) {
        // error 可能有msg属性
        console.error(error);
        Message.error(
          error.msg || (this.formData.id ? "更新失败" : "添加失败")
        );
      } finally {
        this.submitLoading = false;
      }
    },
  },
};
</script>

<style scoped>
.el-form .el-form-item {
  margin-bottom: 26px;
}
.el-radio-group {
  /* space between radio buttons */
  gap: 32px;
}
.el-radio {
  margin-right: 30px;
}

/* 口味选择样式 */
.flavors-container {
  margin-bottom: 16px;
}

.flavor-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.flavor-input {
  flex: 1;
}

.no-flavors {
  text-align: center;
  padding: 20px;
  color: #999;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 16px;
}

.no-flavors-text {
  font-size: 14px;
}

.btn-group {
  margin-top: 8px;
}

/* 删除按钮样式 */
.el-button--danger.is-circle {
  padding: 8px;
  min-width: 32px;
  height: 32px;
}

/* 图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.inline-input {
  flex: 1;
}
</style>
